package com.meshnetics.gb.stack.core.layer;

/**
 * Simple implementation of IDGenerator choosing next available id by incremenally increasing
 * the counter from zero to threshold. When reaching threshold, it starts to generate
 * the id's from zero again.
 *
 * @author mmarkov
 */
public class SimpleIDGenerator implements IDGenerator {
    /**
     * Last busy id integer.
     */
    private int id = 1;

    /**
     * Threshold when start the counter from the beginning.
     */
    private final int maxValue;

    /**
     * Constructs SimpleIDGenerator generating id's in a whole int range.
     */
    public SimpleIDGenerator() {
        maxValue = Integer.MAX_VALUE;
    }

    /**
     * Constructs SimpleIDGenerator having the given threshold.
     *
     * @param maxValue threshold when start the id's counter from the beginning
     */
    public SimpleIDGenerator(int maxValue) {
        if (maxValue < 0) {
            throw new IllegalArgumentException("Negative maximum value");
        }
        this.maxValue = maxValue;
    }

    /**
     * Returns the next available ID.
     *
     * @return the next available ID
     */
    public synchronized int generateID() {
        if (id == maxValue) {
            id = 1;
        } else {
            ++id;
        }
        return id;
    }

    /**
     * Does nothing.
     */
    public void freeID(int id) {
    }
}
